package com.lmt.config.shiro.filter.authz;

import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authz.AuthorizationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

/**
 * 只要拥有任何一个角色即可
 * 一个角色：anyRole[role1]
 * 多个角色中的一个：anyRole["role1,role2"]
 */
public class AnyRoleAuthorizationFilter extends AuthorizationFilter {

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        Subject subject = getSubject(request, response);
        String[] rolesArray = (String[]) mappedValue;

        if (rolesArray == null || rolesArray.length == 0) {
            return true;
        }

        boolean hasRole = false;
        for (String role : rolesArray) {
            if (subject.hasRole(role)){
                hasRole = true;
                break;
            }
        }

        return hasRole;
    }
}
